package com.lizixin.spring.dao;

import com.lizixin.spring.model.User;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * Created by home on 2017/10/29.
 */
@Repository("jdbcUserDao")
public class UserDao implements IUserDao {

    //    Spring提供的JdbcTemplate对jdbc做了封装，大大简化了数据库的操作。
//    如果直接使用JDBC的话，需要我们加载数据库驱动、创建连接、释放连接、
//    异常处理等一系列的动作；繁琐且代码看起来不直观。
//    Spring提供的JdbcTempate能直接数据对象映射成实体类，
//    不再需要获取ResultSet去获取值/赋值等操作，提高开发效率；
    private JdbcTemplate jdbcTemplate;

    @Resource
    public void setDataSource(DataSource dataSource) {
        this.jdbcTemplate = new JdbcTemplate(dataSource);

    }

    public void add(User user) {
        this.jdbcTemplate.update("insert into user (username, password,nickname) values (?,?,?)",
                user.getUsername(), user.getPassword(), user.getNickname());
    }

    public void delete(int id) {
        this.jdbcTemplate.update("delete from user where id = ?", id);
    }

    public void update(User user) {
        this.jdbcTemplate.update(
                "update user set username = ?,password=?,nickname=?  where id = ?",
                user.getUsername(), user.getPassword(), user.getNickname(), user.getId());
    }

    public User load(int id) {
        String sql = "select * from user where id=?";
        User user = jdbcTemplate.queryForObject(sql, new Object[]{id}, new RowMapper<User>() {
            public User mapRow(ResultSet resultSet, int i) throws SQLException {
                User user = new User();
                user.setUsername(resultSet.getString("username"));
                user.setNickname(resultSet.getString("nickname"));
                user.setPassword(resultSet.getString(3));
                user.setId(Integer.parseInt(resultSet.getString(1)));
                user.setId(2);
                return user;
            }
        });
        return user;
    }


    public List<User> list() {
        String sql = "select * from user ";
        List<User> user = jdbcTemplate.query(sql, new RowMapper<User>() {
            public User mapRow(ResultSet resultSet, int i) throws SQLException {
                User user = new User();
                user.setUsername(resultSet.getString("username"));
                user.setNickname(resultSet.getString("nickname"));
                user.setPassword(resultSet.getString("password"));
                user.setId(resultSet.getInt("id"));

                return user;
            }
        });
        return user;
    }


}
